package com.qf.bank.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.bank.dao.AccountMapper;
import com.qf.bank.dao.TransactionRecordMapper;
import com.qf.bank.entity.Account;
import com.qf.bank.entity.TransactionRecord;
import com.qf.bank.response.R;
import com.qf.bank.service.ITransactionRecordService;
import com.qf.bank.vo.input.SearchHistoryInputVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2022-12-03
 */
@Service
public class TransactionRecordServiceImpl extends ServiceImpl<TransactionRecordMapper, TransactionRecord> implements ITransactionRecordService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private TransactionRecordMapper transactionRecordMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    @Transactional
    public R transferAccounts(String userId, Account account) {
        Account self = accountMapper.selectById(userId);
        if (self == null) {
            return R.createFAIL("登录信息有误");
        }
        Account target = accountMapper.selectOne(
                new QueryWrapper<Account>()
                        .eq("cardno", account.getCardno())
        );

        if (target == null) {
            return R.createFAIL("转账失败，磨标账户不存在");
        }
        if (!target.getStatus()) {
            return R.createFAIL("转账失败，目标账户已冻结");
        }
        BigDecimal balance1 = self.getBalance();
        BigDecimal balance2 = account.getBalance();
        /*
         * flag = -1，表示 balance1 小于 balance2。
         * flag =0，表示 balance1 等于 balance2。
         * flag =1，表示 balance1 大于 balance2。
         */
        int result = balance1.compareTo(balance2);
        if (result < 0) {
            return R.createFAIL("转账失败，账户余额不足");
        }

        //扣掉转账的金额
        self.setBalance(self.getBalance().subtract(account.getBalance()));
        int i = accountMapper.updateById(self);
        if (i <= 0) {
            return R.createFAIL("抱歉，转账失败");
        }
        //添加给转账人的金钱
        target.setBalance(target.getBalance().add(account.getBalance()));
        int j = accountMapper.updateById(target);
        if (j <= 0) {
            return R.createFAIL("抱歉，转账失败");
        }

        //添加转账人的扣费记录
        TransactionRecord expense = new TransactionRecord();
        expense.setCardno(self.getCardno());
        expense.setTransactionDate(new Date());
        expense.setExpense(account.getBalance());
        expense.setBalance(self.getBalance());
        expense.setTransactionType("消费");
        expense.setRemark("一笔支出");
        int i1 = transactionRecordMapper.insert(expense);
        if (i1 <= 0) {
            return R.createFAIL("抱歉，转账失败");
        }

//        System.out.println(1/0);

        //添加收款人的收费记录
        TransactionRecord income = new TransactionRecord();
        income.setCardno(target.getCardno());
        income.setTransactionDate(new Date());
        income.setIncome(account.getBalance());
        income.setBalance(target.getBalance());
        income.setTransactionType("存款");
        income.setRemark("一笔收入");
        int i2 = transactionRecordMapper.insert(income);
        if (i2 <= 0) {
            return R.createFAIL("抱歉，转账失败");
        }

        return R.createSuccess("转账成功");
    }

    @Override
    public R searchHistory(String userId, SearchHistoryInputVo inputVo) {
        Account account = accountMapper.selectById(userId);
        if (account == null) {
            return R.createFAIL("登录信息有误");
        }

        Date startTime = inputVo.getStartTime();
        Date endTime = inputVo.getEndTime();

        if (startTime == null || endTime == null) {
            return R.createFAIL("请将查询时间填写完整");
        }

        //判断日期时间是否合法
        int flag = startTime.compareTo(endTime);
        if (flag > 0) {
            return R.createFAIL("您输入的日期范围不合法");
        }

        //开启分页的功能
        PageHelper.startPage(inputVo.getPageNum(), inputVo.getPageSize());
        //查询数据
        List<TransactionRecord> transactionRecords = transactionRecordMapper.selectList(
                new QueryWrapper<TransactionRecord>()
                        .eq("cardno", userId)
                        .and(i -> i.ge("transaction_date", startTime)
                                .le("transaction_date", endTime))
                        .orderByDesc("transaction_date")
        );
        //处理分页的问题
        PageInfo<TransactionRecord> info = new PageInfo<>(transactionRecords);

        return R.createSuccess(info);
    }
}
